package com.Spring.liaojp.config;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author LiaoJianpeng
 *
 * &#064;date  2020/3/31 - 14:09
 * &#064;Description:  初始化数据库
 */
public class DataBaseInitializer {
    private final String url;

    private final String user;

    private final String password;

    public static  Connection connection;

    public DataBaseInitializer(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.password = password;
    }

    public void init()
    {
        System.out.println("初始化数据库");

        try {
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功");

            Statement statement = connection.createStatement();
            // todo 执行.sql脚本
//            // 删除订单表
//            statement.execute("DROP TABLE IF EXISTS `order`");
//            // 创建订单表
//            statement.execute("CREATE TABLE IF NOT EXISTS `order`(" +
//                    "order_id int(5) AUTO_INCREMENT PRIMARY KEY," +
//                    "`need` INT(6) NOT NULL ," +
//                    "price DECIMAL(10, 2) NOT NULL " +
//                    ")");
//            // 插入数据
//            statement.execute("INSERT INTO `order`(need, price) VALUES (100, 101)");
//            statement.execute("INSERT INTO `order`(need, price) VALUES (200, 201)");
//            statement.execute("INSERT INTO `order`(need, price) VALUES (300, 301)");
//            statement.execute("INSERT INTO `order`(need, price) VALUES (400, 401)");
        } catch (SQLException e) {
            System.out.println("数据库连接失败");
            throw new RuntimeException(e);
        }
    }
}
